// pages/order/order.js
import {DECIMAL_GOOD_INDEX} from '../../config/index.js'

var app = getApp();

const HaveEatWay = {
  UNDEFINE: 0,
  HERE: 1,
  OUT: 2,
};

Page({

  /**
   * 页面的初始数据
   */
  data: {
    hereSelected: HaveEatWay.UNDEFINE, // 0：未选择，1：堂食，2，打包
    howToEat: {
      visible: false,
      title: '请选择就餐方式',
      items: [{
          label: '堂食',
        },
        {
          label: '打包',
        }
      ]
    },
    urlEatAtHere: "",
    urlEatAtThere: "",
    currentOrderStatus: '未完成订单',
    globalData: '',
    shops: '',
    DECIMAL_GOOD_INDEX: DECIMAL_GOOD_INDEX,
    dynamicColor: 'white',
    toPayButtonDisabled: true,
    showAdditionalGoods: false,
    orderNo: null
  },

  switchToHereEat() {
    this.setData({
      hereSelected: 1
    })
    app.data.globalData.order.unpay.postType = this.data.hereSelected;
    
    this._calcTotalPrice(this.data.globalData.order.unpay)
  },

  switchToThereEat() {
    this.setData({
      hereSelected: 2
    })
    app.data.globalData.order.unpay.postType = this.data.hereSelected;
    this._calcTotalPrice(this.data.globalData.order.unpay)
  },

  _calcTotalPrice(order) {
    var total = 0;
    // 重新计算打包费
    this._addAdditionalGoods();
    let needAddPrice;
    if(this.data.hereSelected === HaveEatWay.OUT){
      needAddPrice = true;
    }

    if (order && order.goods) {
      order.goods.forEach(function (item) {
        let _newPrice = item.price;
        if(needAddPrice){
          _newPrice += item.addPrice;
        }
        total += Math.round(_newPrice * item.count);
      });
    }
    if(order && order.addGoods){
      order.addGoods.forEach(function (item) {
        total += Math.round(item.price * item.count);
      });
    }
    this.setData({
      'globalData.order.unpay.totalPrice': total,
    })
    // 设置
    if(total > 0){
      this.setData({
        toPayButtonDisabled: false
      })
    }else{
      this.setData({
        toPayButtonDisabled: true
      })
    }
  },

  quantityPlus(e){
    console.log(e)
    this._handlePlus(e.detail.index);
  },
  quantityMinus(e){
    console.log(e)
    this._handleMinus(e.detail.index);
  },
  quantityInput(e){
    console.log(e)
    let {value, index} = e.detail;
    this._handleInput(index, value)
  },
  quantityDelete(e){
    console.log(e)
    this._handleDelete(e.detail.index)
  },

  // 加号按钮事件
  _handlePlus(index=0) {
    const goods = this.data.globalData.order.unpay.goods;
    goods[index].count += 1; // 修改对应商品的数量
    this.setData({
      'globalData.order.unpay.goods': goods,
    });
    console.log('加号按钮点击，索引:', index);
    // 更新总价
    this._calcTotalPrice(this.data.globalData.order.unpay);
    app._refreshAllGoodsList(goods[index].id, goods[index].count);
  },

  // 减号按钮事件
  _handleMinus(index) {
    const goods = this.data.globalData.order.unpay.goods;
    if (goods[index].count > 0) {
      let id = goods[index].id;
      let count;
      goods[index].count -= 1; // 修改对应商品的数量
      count = goods[index].count;
      app._refreshAllGoodsList(goods[index].id, goods[index].count);
      
      if (goods[index].count === 0) {
        goods.splice(index, 1);
      }
      this.setData({
        'globalData.order.unpay.goods': goods,
      });
    }
    console.log('减号按钮点击，索引:', index);

    // 更新总价
    this._calcTotalPrice(this.data.globalData.order.unpay);
  },

  _handleDelete(index) {
    const goods = this.data.globalData.order.unpay.goods;

    app._refreshAllGoodsList(goods[index].id, 0);

    // 删除对应索引的商品
    goods.splice(index, 1);
    // 更新数据
    this.setData({
      'globalData.order.unpay.goods': goods,
    });

    console.log('删除商品，索引:', index);
    // 更新总价
    this._calcTotalPrice(this.data.globalData.order.unpay);
  },

  // 输入商品数量
  _handleInput(index, value) {
    const goods = this.data.globalData.order.unpay.goods;
    goods[index].count = value;
    
    app._refreshAllGoodsList(goods[index].id, goods[index].count);

    if(value === 0){
      goods.splice(index, 1);
    }
    this.setData({
      'globalData.order.unpay.goods': goods,
    });

    // 更新总价
    this._calcTotalPrice(this.data.globalData.order.unpay);
  },

  handleContinue() {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },

  handlePay() {
    var that = this;

    if(this.data.hereSelected === HaveEatWay.UNDEFINE){
      this.setData({
        'howToEat.visible': true
      })
      this.waitForSelection().then(() => {
        // 如果是打包，需要添加打包费
        this._calcTotalPrice(this.data.globalData.order.unpay);
        // 这里跳转到支付
        console.log('选择了就餐方式，跳转到支付')
        that.handlePay();
      }).catch(() => {
        console.log('用户未选择就餐方式');
      });
    }else if(app.data.shops.index === 0){
      wx.navigateTo({
        url: '/pages/choice-shop/index',
      })
    }else{
      // 这里跳转到支付
      console.log('跳转到支付')
      // 如果订单id为空，加工订单id
      if(!this.data.globalData.order.unpay.id){
        this.data.globalData.order.unpay.id = Date.now();
      }
      wx.request({
        url: app.data.global_urls.getPrepayUrl(),
        method: 'POST',
        header:{
          'Authorization': `Bearer ${app.data.loginData.token}`,
          'content-type': 'application/json'
        },
        data:{
          shopId: app.data.shops.index,
          unpay: this.data.globalData.order.unpay
        },
        success(res){
          wx.hideToast();

          if(10024 === res.data.status){
            // 需要重新登录
            console.log(" inSuccess: 需要重新登录", res)
            app._needReLogin(null, that._loginCallBackInOrderPage.bind(that));
          }else if(10000 !== res.data.status){
            // 数据库插入失败，稍后重试
            console.log(" inSuccess: 获取预支付信息失败", res)
            wx.showToast({
              title: '内部服务错误，请稍后再试',
              icon: 'error',
              duration: 3000,
              mask: true
            });
          }else{
            // 订单创建成功，清除unpay.id，避免id重复
            if(res.data.data.orderNo){
              console.log('后端订单创建成功，orderNo = ', res.data.data.orderNo);
              that.data.orderNo = res.data.data.orderNo;
              let prepayArg = res.data.data.prepayWithRequestPaymentResponse;
              if(prepayArg){
                // 获取预支付信息成功
                console.log("获取预支付信息成功，拉起支付", prepayArg)
                app._doPay(prepayArg, that._doPayCompleteCallBack.bind(that));
              }else{
                // 获取腾讯预支付信息失败，跳转到订单详情页面，继续付款
                console.log("请求预支付失败，需要跳转到订单详情页面")
                that._doPayCompleteCallBack();
              }
            }else{
              // 按理不应该到达
              console.log(" inSuccess: 获取预支付信息失败", res)
              wx.showToast({
                title: '内部服务错误，请稍后再试',
                icon: 'error',
                duration: 1500,
                mask: true
              });
            }
          }
        },
        fail(e){
          console.log("inFail: 获取预支付信息失败", e)
          wx.hideToast();
          wx.showToast({
            title: '下单失败，请稍后再试',
            icon: 'error',
            duration: 1500,
            mask: true
          });
        }
      })

      // 立即支付设置disable，toast加载中，如果预支付成功，说明订单生成，删除unpay中的数据，allGoodsList的count清零
      // this.setData({
      //   toPayButtonDisabled: true
      // })
      wx.showToast({
        title: '订单提交中',
        icon: 'loading',
        duration: 10000,
        mask: true
      })
    }
  },

  _loginCallBackInOrderPage(data){
    // 继续发起支付
    this.handlePay();
  },

  _doPayCompleteCallBack(){
    this._clearCurrentUnpayOrder();
    wx.navigateTo({
      url: `/pages/order-detail/order-detail?orderNo=${this.data.orderNo}`,
    })
  },

  handleSelected(e) {
    var index = e.detail.index;
    this.setData({
      hereSelected: index + 1,
      'howToEat.visible': false
    })
    app.data.globalData.order.unpay.postType = this.data.hereSelected;
    if(this.selectionResolve){
      console.log('promise执行完成,resolve')
      this.selectionResolve();
    }
  },

  handleActionSheetClose(e){
    console.log('action sheet 关闭', e)
    this.setData({
      'howToEat.visible': false
    })
    if(this.selectionResolve){
      console.log('清理promise的resolve和reject')
      this.selectionResolve = null;
    }
    if(this.selectionReject){
      console.log('清理promise的resolve和reject')
      this.selectionReject = null;
    }
  },

  // 封装用户选择的逻辑为 Promise
  waitForSelection() {
    console.log('创建promise')
    return new Promise((resolve, reject) => {
      // 将 resolve 和 reject 挂载到 this 上，供 handleSelected 调用
      this.selectionResolve = resolve;
      this.selectionReject = reject;
    });
  },

  _clearCurrentUnpayOrder(){
    this.data.globalData.order.unpay = {
      id: null,
      totalPrice: 0,
      goods:[],
      addGoods: [],
      postType: 0
    };
    this.data.globalData.allGoodsList.forEach((item) => {
      item.count = 0.0;
    })
    this.setData({
      globalData: this.data.globalData
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getTabBar().init();
    this.setData({
      urlEatAtHere: app.data.global_urls.urlEatAtHere,
      urlEatAtThere: app.data.global_urls.urlEatAtThere,
      globalData: app.data.globalData,
      hereSelected: app.data.globalData.order.unpay.postType,
      shops: app.data.shops
    })
    
    this._calcTotalPrice(this.data.globalData.order.unpay)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  /**
   * 添加打包费
   */
  _addAdditionalGoods(){

    return;

    var that = this;
    if(this.data.hereSelected != HaveEatWay.OUT){
      this.setData({
        'globalData.order.unpay.addGoods': []
      })
      return;
    }

    let addGoods = [];
    this.data.globalData.order.unpay.goods?.forEach((item) => {
      if(item.id === 2){
        addGoods.push({
          ...that.data.globalData.additionalGoods[0],
          count: item?.count
        })
      }else if(item.id === 3){
        addGoods.push({
          ...that.data.globalData.additionalGoods[1],
          count: item?.count
        })
      }
    })

    // 设置addGoods
    this.setData({
      'globalData.order.unpay.addGoods': addGoods
    })
    console.log('添加打包费', this.data.globalData)
  }
})